<template>
  <div class="wechat-layout">
    <!-- 左侧联系人列表 -->
    <div class="contact-list">
      <div class="chat-header">
        <img :src="userAvatar" alt="个人" class="avatar" />
        {{ getName() }}
      </div>
      <div
          v-for="contact in processedContacts"
          :key="contact.id"
          class="contact-item"
          :class="{ active: activeContactId === contact.id }"
          @click="selectContact(contact)"
      >
        <div class="avatar">
          <img :src="getAvatarUrls(contact)" alt="头像" class="avatar-img" />
        </div>
        <div class="contact-info">
          <div class="name-time">
            <div class="name">{{ contact.name }}</div>
            <div class="last-message-time">{{ getLastMessageTime(contact) }}</div>
          </div>
          <span class="last-message">{{ getLastMessage(contact) }}</span>
          <span v-if="getUnreadCount(contact) > 0" class="unread-count">
            {{ getUnreadCount(contact) }}
          </span>
        </div>
      </div>
    </div>

    <!-- 右侧聊天框 -->
    <div class="chat-box">
      <div class="chat-messages">
        <div
            v-for="message in activeContact.messages"
            :key="message.id"
            class="message-wrapper"
            :class="{ 'message-right': message.isMe }"
        >
          <!-- 头像 -->
          <div class="message-avatar">
            <img :src="getAvatarUrl(message)" alt="头像" class="avatar-img" />
          </div>
          <!-- 消息内容 -->
          <div class="message-content">
            <div>{{ message.content }}</div>
          </div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
      <div class="chat-input">
        <input
            v-model="newMessage"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
        />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'; // 引入axios

export default {
  data() {
    const userData = localStorage.getItem("user");
    let currentUserId = "";
    let userAvatar = require("@/assets/img/logo.png");
    let Administrator = require("@/assets/img/logo.png");

    if (userData) {
      try {
        // 根据实际存储格式调整解析逻辑
        currentUserId = userData.split(',')[0]; // 假设userData格式为 "userId,其他信息"
      } catch (e) {
        console.error("用户信息解析失败:", e);
      }
    }

    return {
      processedContacts: [], // 初始化为空数组
      activeContactId: null,
      newMessage: "",
      userAvatar,
      currentUserId,
      Administrator
    };
  },
  computed: {
    activeContact() {
      return this.processedContacts.find(c => c.id === this.activeContactId) || { messages: [] };
    }
  },
  created() {
    this.fetchMessages(); // 组件创建时获取数据
  },
  methods: {
    async fetchMessages() {
      try {
        const config = {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("userToken")}`
          }
        };

        // 使用当前用户ID动态构造请求地址
        const response = await axios.get(
            `http://localhost:8080/api/messages/admin/all/665750`,
            config
        );

        // 处理接口返回数据
        const apiData = response.data.data;
        this.processedContacts = this.processApiData(apiData);

        // 设置默认选中第一个联系人
        if (this.processedContacts.length > 0) {
          this.activeContactId = this.processedContacts[0].id;
          // 循环打印每个消息的 id
          this.processedContacts[0].messages.forEach(message => {
            if (!message.isMe) {
              this.markMessagesAsRead(message.id, this.processedContacts[0]);
            }
          });
        }
      } catch (error) {
        console.error("获取消息失败:", error);
        // 可以添加错误提示逻辑
      }
    },
    getName(){
      return "665750";
    },
    processApiData(apiData) {
      return Object.entries(apiData).map(([id, contactData]) => ({
        id,
        name: contactData.name,
        messages: contactData.messages.map(msg => ({
          id: msg.id,
          content: msg.messageText,
          time: msg.createdAt.split(' ')[1].substring(0, 5),
          isMe: msg.adminId === null && String(msg.userId) === this.currentUserId,
          users: msg.users,
          recipien: msg.recipien,
          isRead: msg.isRead
        }))
      }));
    },
    getAvatarUrl(message){
      return message.isMe ? (message.users[0].avatar || this.userAvatar) : (message.recipien?.[0] ? (message?.recipien?.[0]?.avatar || this.userAvatar) : this.Administrator);
    },
    getAvatarUrls(mes){
      let message = mes.messages[0];
      if (mes.name === "管理员")
        return this.Administrator; // 如果是管理员，显示管理员头像
      else
        return message.isMe ? (message.users[0].avatar || this.userAvatar) : (message.recipien?.[0] ? (message?.recipien?.[0]?.avatar || this.userAvatar) : this.Administrator);
    },
    getLastMessageTime(contact) {
      if (contact.messages.length > 0) {
        return contact.messages.slice(-1)[0].time;
      }
      return "";
    },
    getUnreadCount(contact) {
      return contact.messages.filter(msg => !msg.isRead && !msg.isMe).length;
    },
    getLastMessage(contact) {
      return contact.messages.length > 0
          ? contact.messages.slice(-1)[0].content
          : "[无消息]";
    },
    selectContact(contactId) {
      this.activeContactId = contactId.id;

      // 将当前联系人消息设置为已读
      contactId.messages.forEach(message => {
        if (!message.isMe) {
          this.markMessagesAsRead(message.id, contactId);
        }
      });
    },
    async markMessagesAsRead(contactId,contact) {
      try {
        const config = {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem("userToken")}`,
          }
        };

        // 调用接口标记消息为已读
        const response = await axios.post(
            `http://localhost:8080/api/messages/markAsRead/${contactId}`,
            {}, // 如果接口需要请求体，可以添加
            config
        );

        if (response.data.code === 200) {
          console.log(`联系人 ${contactId} 的消息已标记为已读`);
          // 更新本地数据，确保响应式更新
          contact.messages = contact.messages.map(msg => {
            if (msg.id === contactId) {
              return { ...msg, isRead: true };
            }
            return msg;
          });
        } else {
          console.error('标记已读失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求错误:', error);
      }
    },
    sendMessage() {
      if (!this.newMessage.trim()) {
        alert("请输入内容")
        return;
      }

      const message = {
        userId: parseInt(this.currentUserId, 10),  // 确保是整数类型
        recipientId: parseInt(this.activeContactId, 10) || null,  // 确保是整数类型
        messageType: 'text', // 消息类型，'text' 或 'image'
        messageText: this.newMessage, // 消息内容
        isRead: false, // 新消息标记为未读
      };

      const config = {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem("userToken")}`,
        }
      };

      // 发送 POST 请求到后台接口
      axios.post('http://localhost:8080/api/messages/send', message, config)
          .then(response => {
            if (response.data.code === 200) {
              // 添加本地消息
              const now = new Date();
              const time = now.toTimeString().substring(0, 5);

              this.activeContact.messages.push({
                id: Date.now(), // 临时ID
                content: this.newMessage,
                time: time,
                isMe: true,
                users: [{ avatar: this.userAvatar }],
                recipien: [],
                isRead: true
              });

              this.newMessage = ''; // 清空输入框
              this.$nextTick(() => {
                // 自动滚动到底部（可选）
                const container = this.$el.querySelector(".chat-messages");
                container.scrollTop = container.scrollHeight;
              });
            } else {
              console.error('发送失败:', response.data.msg);
            }
          })
          .catch(error => {
            console.error('请求错误:', error);
          });
    }
  }
};
</script>

<style scoped>
.avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover; /* 保持图片比例 */
}

.wechat-layout {
  display: flex;
  height: 65vh;
  background-color: #f5f5f5;
}

.contact-list {
  width: 300px;
  background-color: #fff;
  border-right: 1px solid #ddd;
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.contact-item.active {
  background-color: #f0f0f0;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  margin-right: 10px;
}

.contact-info {
  flex: 1;
}

.name-time {
  display: flex;
  justify-content: space-between;
}

.last-message-time {
  font-size: 12px;
  color: #888;
}

.unread-count {
  float: right;
  background-color: red;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  margin-top: 2px;
  align-self: flex-end;
}

.name {
  font-weight: bold;
}

.last-message {
  font-size: 12px;
  color: #888;
}

.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.chat-header {
  padding: 10px;
  border-bottom: 1px solid #ddd;
  font-weight: bold;
  background-color: #f9f9f9;
  display: flex;
  align-items: center;
}

.header-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #4caf50;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.header-name {
  font-size: 16px;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.message-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-avatar .avatar-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover; /* 保持图片比例 */
}

.message-content {
  max-width: 60%;
  padding: 8px 8px;
  border-radius: 5px;
  background-color: #e0e0e0;
  margin: 0 10px;
}

.message-right {
  flex-direction: row-reverse;
}

.message-right .message-content {
  background-color: #4caf50;
  color: #fff;
}

.message-time {
  color: #888;
  margin-top: 4px;
}

.chat-input {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
  background-color: #f9f9f9;
}

.chat-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-right: 10px;
}

.chat-input button {
  padding: 8px 12px;
  background-color: #4caf50;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #45a049;
}
</style>
